package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    private SysUserService service;
    @Autowired
    private SysRoleService roleService;
    @PostMapping("/login")
    public String login(Model model, HttpServletRequest request, String account, String password){
        SysUser user = service.login(account,password);
        if (user == null){
            model.addAttribute("error","用户名或密码错误");
            return "login";
        }
        request.getSession().setAttribute("userSession",user);
        return "redirect:/frame";
    }
    @RequestMapping("/queryUser")
    public String queryUser(Model model,@RequestParam(required = false,defaultValue = "") String realName,@RequestParam(required = false,defaultValue = "0") Integer roleId, @RequestParam(required = false,defaultValue = "1") int pageIndex, @RequestParam(required = false,defaultValue = "3") int pageSize){
//        model.addAttribute("msg",);
        List<SysUser> queryUserList = service.queryList(realName,roleId,pageIndex,pageSize);
        List<SysRole> roleList = roleService.roleList();
        int listSize = service.getListSize(realName,roleId);
        model.addAttribute("queryUserList",queryUserList);
        model.addAttribute("roleList",roleList);
        model.addAttribute("realName",realName);
        model.addAttribute("roleId",roleId);
        model.addAttribute("pageIndex",pageIndex);
        model.addAttribute("pageCount",(listSize % pageSize == 0 ? (listSize / pageSize) : (listSize/pageSize) + 1));
        model.addAttribute("roleId",roleId);
        model.addAttribute("count",listSize);
        return "sysUser/sysUserList";
    }
    @RequestMapping("/toAdd")
    public String toAdd(Model model){
        model.addAttribute("roleList",roleService.roleList());
        model.addAttribute("opr","add");
        return "sysUser/addSysUser";
    }
    @RequestMapping("/add")
    public String add(HttpServletRequest request,Model model, @Valid SysUser user, BindingResult bindingResult,@RequestParam(required = false) MultipartFile idPic){
        if (bindingResult.hasErrors()){
            String msgName = bindingResult.getFieldErrors().get(0).getField();
            String msg = bindingResult.getFieldErrors().get(0).getDefaultMessage();
            System.out.println(msgName+":"+msg);
            return "redirect:/user/toAdd";
        }

        try {
            String fileName = idPic.getOriginalFilename();
            System.out.println("文件名"+fileName);
            String suffix = FilenameUtils.getExtension(fileName);
            String pathName = request.getSession().getServletContext().getRealPath("static" + File.separator + "uploadFiles");
            String targetFileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + suffix;
            File targetFile = new File(pathName,targetFileName);
            idPic.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        service.add(user);
        return "redirect:/user/queryUser";
    }
    @RequestMapping("/info")
    public String info(Model model,int id){
        model.addAttribute("user",service.selectSysUser(id));
        return "sysUser/info";
    }
    @RequestMapping("/toUpdate")
    public String toUpdate(Model model,int id){
        model.addAttribute("user",service.selectSysUser(id));
        model.addAttribute("roleList",roleService.roleList());
        model.addAttribute("opr","update");
        return "sysUser/addSysUser";
    }
    @RequestMapping("/update")
    public String update(Model model,SysUser user){
        service.modify(user);
//        model.addAttribute("msg","更新成功！");
        return "redirect:/user/queryUser";
    }
    @RequestMapping("/delete")
    public String delete(Model model,int id){
        service.del(id);
//        model.addAttribute("msg","更新成功！");
        return "redirect:/user/queryUser";
    }
    @ResponseBody
    @RequestMapping("/validateAccount")
    public Object validateAccount(String account){
        boolean r = service.validateAccount(account);
        String validate = JSON.toJSONString(r);
        return validate;
    }
}
